import axios from 'axios'
import config from '~/config'

axios.defaults.baseURL = config.BASE_URL
axios.defaults.timeout = config.TIMEOUT
axios.defaults.headers = config.HEADERS

const cookie = process.client ? require('js-cookie') : undefined

const myaxios=axios.create({
  baseURL: config.BASE_URL, // 所有异步请求都加上/api,nginx转发到后端Springboot
  withCredentials: true, // send cookies when cross-domain requests
  timeout: config.TIMEOUT // request timeout
})

// 请求拦截器
myaxios.interceptors.request.use(
  config=>{
    if(cookie){
      let token=cookie.get("auth")
      if(token){
        config.headers={
          'Authorization': `Token ${token}`
        }
      }
    }
    return config
  },
  request => {
    if (!config.IS_RELEASE) {
      console.log(
        `${new Date().toLocaleString()}【 M=${request.url} 】P=`,
        request.params || request.data
      )
    }
    return request
  },
  error => {
    return Promise.reject(error)
  }
)

export default async (options = { method: 'GET' }) => {
  let isdata = true
  if (
    options.method.toUpperCase() !== 'POST' &&
    options.method.toUpperCase() !== 'PUT' &&
    options.method.toUpperCase() !== 'PATCH'
  ) {
    isdata = false
  }
  const res = await axios({
    method: options.method,
    url: options.url,
    data: isdata ? options.data : null,
    params: !isdata ? options.data : null
  })
  if (res.status == 200) {
    if (!config.IS_RELEASE) {
      console.log(`${new Date().toLocaleString()}【接口响应：】`, res.data)
    }
    // 浏览器环境弹出报错信息
    if (typeof window !== 'undefined' && res.data.code !== 0) {
      //alert(res.data.msg)
    }
    return res.data
  } else {
    if (typeof window !== 'undefined' && res.data.code !== 0) {
      alert(res.data.msg + '请求错误')
    }
  }
}
